package com.bwie.realtime.jtp.dwd.log.gd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.bwie.realtime.jtp.utils.DateTimeUtil;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.kerby.cms.type.KeyDerivationAlgorithmIdentifier;

public class AdjustIsNewProcessFunction extends KeyedProcessFunction<String, String, String> {
    private transient ValueState<String> firstDateState= null;

    @Override
    public void open(Configuration parameters) throws Exception {
        firstDateState = getRuntimeContext().getState(
                new ValueStateDescriptor<String>("first-date", String.class)
        );
    }

    @Override
    public void processElement(String s, KeyedProcessFunction<String, String, String>.Context context, Collector<String> collector) throws Exception {
        ValueState<String> firstDate = firstDateState;
        JSONObject jsonObject = JSON.parseObject(s);
        String isNewValue = jsonObject.getJSONObject("common").getString("is_new");
        Long tsValue = jsonObject.getLong("ts");
        if("1".equals(isNewValue)){
            if (null == firstDate){
                firstDateState.update(DateTimeUtil.convertLongToString(tsValue, DateTimeUtil.DATE_FORMAT));
            }
            else {
                if (!firstDate.equals(DateTimeUtil.convertLongToString(tsValue, DateTimeUtil.DATE_FORMAT))){
                    jsonObject.getJSONObject("common").put("is_new","0");
                }
            }
        }
        else {
            if (null == firstDate){
                firstDateState.update(DateTimeUtil.convertLongToString(tsValue-86400000, DateTimeUtil.DATE_FORMAT));
            }
        }
        collector.collect(jsonObject.toJSONString());


    }
}
